package com.chatroom.controller;

import com.chatroom.dto.MessageDTO;
import com.chatroom.model.ChatRoom;
import com.chatroom.model.Message;
import com.chatroom.model.PrivateChatRoom;
import com.chatroom.model.User;
import com.chatroom.service.ChatRoomService;
import com.chatroom.service.MessageService;
import com.chatroom.service.PrivateChatRoomService;
import com.chatroom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/messages")
public class MessageController {

    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);
    private final MessageService messageService;
    private final UserService userService;
    private final ChatRoomService chatRoomService;
    private final PrivateChatRoomService privateChatRoomService;

    @Autowired
    public MessageController(MessageService messageService, UserService userService, 
                           ChatRoomService chatRoomService, PrivateChatRoomService privateChatRoomService) {
        this.messageService = messageService;
        this.userService = userService;
        this.chatRoomService = chatRoomService;
        this.privateChatRoomService = privateChatRoomService;
    }

    @GetMapping("/privatechat/{roomCode}")
    public ResponseEntity<?> getPrivateChatRoomMessages(@PathVariable String roomCode) {
        logger.info("获取私聊房间 {} 的消息", roomCode);
        
        Optional<PrivateChatRoom> privateChatRoomOpt = privateChatRoomService.findByRoomCode(roomCode);
        
        if (privateChatRoomOpt.isPresent()) {
            PrivateChatRoom privateChatRoom = privateChatRoomOpt.get();
            User user1 = privateChatRoom.getUser1();
            User user2 = privateChatRoom.getUser2();
            
            logger.info("找到私聊房间 {}, 用户: {} 和 {}", roomCode, user1.getUsername(), user2.getUsername());
            
            // 获取这两个用户之间的所有私聊消息
            List<MessageDTO> messages = messageService.getPrivateMessages(user1, user2).stream()
                    .map(message -> {
                        MessageDTO dto = new MessageDTO(message);
                        dto.setRoomCode(roomCode);  // 设置房间号
                        return dto;
                    })
                    .collect(Collectors.toList());
            
            logger.info("找到 {} 条私聊消息", messages.size());
            return ResponseEntity.ok(messages);
        } else {
            logger.warn("未找到房间号为 {} 的私聊房间", roomCode);
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/private")
    public ResponseEntity<?> getPrivateMessages(@RequestParam Long user1Id, @RequestParam Long user2Id) {
        Optional<User> user1Opt = userService.findById(user1Id);
        Optional<User> user2Opt = userService.findById(user2Id);
        
        if (user1Opt.isPresent() && user2Opt.isPresent()) {
            List<MessageDTO> messages = messageService.getPrivateMessages(user1Opt.get(), user2Opt.get()).stream()
                    .map(MessageDTO::new)
                    .collect(Collectors.toList());
            return ResponseEntity.ok(messages);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/group/{roomCode}")
    public ResponseEntity<?> getChatRoomMessages(@PathVariable String roomCode) {
        Optional<ChatRoom> chatRoomOpt = chatRoomService.findByRoomCode(roomCode);
        
        if (chatRoomOpt.isPresent()) {
            List<MessageDTO> messages = messageService.getChatRoomMessages(chatRoomOpt.get()).stream()
                    .map(MessageDTO::new)
                    .collect(Collectors.toList());
            return ResponseEntity.ok(messages);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
} 